<?php

namespace App\Console;

use App\Console\Commands\Cruise\SyncCruiseOrderProjectLazyCommand;
use App\Console\Commands\Invoice\InvoiceSyncHeaderCommand;
use App\Library\FeiShu\SendFs;
use App\Service\Push\PushConfigService;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Kuafu\IpWhite\Command\FlushIps;
use Kuafu\IpWhite\Command\ForceLoginOut;
use Kuafu\IpWhite\Command\TotalLists;
use Kuafu\IpWhite\Command\UserLists;
use KuafuComposer\ApiTime\Command\ApiTimeBatchPushCommand;
use KuafuComposer\ApiTime\Command\ApiTimePushCommand;

class Kernel extends ConsoleKernel
{
    protected $commands = [
        ApiTimePushCommand::class,
        ApiTimeBatchPushCommand::class,
        ForceLoginOut::class,
        UserLists::class,
        TotalLists::class,
        FlushIps::class,
        InvoiceSyncHeaderCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // NSQ监控
        $schedule->command('nsq:monitor-nsq-server')->everyMinute()->runInBackground();

        //夏季专项选址推送
//        $schedule->command('siteLocation:summer-site-robot-push team')->dailyAt("08:40");
//        $schedule->command('siteLocation:summer-site-robot-push personal')->dailyAt("12:00");
        $schedule->command('siteLocation:guanyuan-refresh-url')->everyMinute()->runInBackground();

        // $schedule->command('inspire')->hourly();
        $schedule->command('feishuCallingCards:updateEmployeeDepartment')->dailyAt("02:00");

        // 推送昨日慢接口日志
        $schedule->command('api-time:push-slow-api --fsRobot=' . SendFs::ROBOT_API_TIME)->dailyAt("09:10");

        // 对账
        $schedule->command('check:create-check-stream')->dailyAt('10:01');

        // 开店待支付订单催付
//        $schedule->command('openShop:notice-pay')->dailyAt('11:00');

        // 每周日、三、五 8点 推送 日拱一卒 （暂停推送@since 20220615）
//        $schedule->command('open_shop:order_sign_statistical_weeks')->cron('0 8 * * 0,3,5');

        // 每周日、三、五 8 点推送 日拱一卒 (暂停推送)
//        $schedule->command('open_shop:order_sign_statistical_month')->cron('1 8 * * 0,3,5');

        if (isProd() || config('app.env') == 'pre') {//新增pre环境跑脚本 推送到测试群
            // 每日 21:10 推送 签约数据
            $schedule->command('open_shop:order_sign_new_sign_daily')->dailyAt('21:10');
        }
        // 每日 21:10 推送 商家增长【数据追踪】
        $schedule->command('open_shop:shang_zeng_daily')->dailyAt('21:10');
        // 每日 22:00 推送当日 选址审核记录
        //$schedule->command('open_shop:site_location_examine_cycle --cycle=daily')->cron('0 22 * * *');
        // 每周一 09:00 推送上周 选址审核记录
        $schedule->command('open_shop:site_location_examine_cycle --cycle=weekly')->cron('0 9 * * 1');
        // 每月1号09:00 推送上月 选址审核记录
        $schedule->command('open_shop:site_location_examine_cycle --cycle=monthly')->cron('0 9 1 * *');


        // 每天0:35,01:35,02:35,03:35 同步8天内的云直连招商银行流水单到check_cmb_bank_flows表里面
        $schedule->command('check:sync_cmb_bank_flow')->cron('35 0,1,2,3 * * *')->runInBackground();

        // 每天02:00生成年费订单
        $schedule->command('fee:create-annual-fee-order')->cron('0 2 * * *');

        /******* 通过 SubFsUserAddCommand nsq 做实时更新 *******/
        // 每天刷新省区开发人员
        $schedule->command('openShop:refresh-province-developers')->dailyAt("02:05");

        // 每天刷新招商人员
        $schedule->command('openShop:refresh-solicit-business')->dailyAt("02:35");
        /****************************************************************/

        // 每天7:00推送消息
        $schedule->command('fee:push-annual-fee-order')->cron('0 7 * * *');

        // 每天8:00推送排行榜消息
        $schedule->command('openShop:site-ranking-list-notify')->cron('0 8 * * *');

        // 每天5:00同步近30天营业额与订货金额
        $schedule->command('cruise:update-shop-order-amount')->cron('0 5 * * *');

        //年费订单过期关闭脚本
        // $schedule->command('fee:order-overdue-close')->cron('0 */1 * * *');

        // 删除公开OSS下面 tmp/2022xxxx/下面的旧文件，目前是删除3天前的
        $schedule->command('system:clear_old_oss_files')->daily();

        // 更新外部人员的fs_company_users表信息
        $schedule->command('user:ext-user-update-v2')->dailyAt("03:00");

        // 每10分钟更新一次（作废已过期任务）
        $schedule->command('cruise:check_order_cancel')->everyTenMinutes();

        // 每分钟更新一次（文件转码结果）
        $schedule->command('common:update-file-transcoding-result')->everyMinute();

        // 每天02:00自动更新培训计划状态
        $schedule->command('college:update-training-plans-status')->cron('0 2 * * *');

        // 定期清理resources软删除记录
        $schedule->command('common:clear-resources')->dailyAt("03:05");

        // 个人、省区、总部任务推送.
//        foreach (PushConfigService::BIZ_LISTS as $bizType) {
//            $schedule->command('push:task ' . $bizType)->dailyAt("08:00");
//        }
        $schedule->command('push:task ' . PushConfigService::BIZ_TYPE_USER)->dailyAt("07:50");

        // 每天08:00违约函到期自动发送商家消息
        $schedule->command('cruise:cruise_check_against_send_notify')->dailyAt("08:00");

        //每半小时执行 更新退款单状态
        $schedule->command('ekb:pollingApproveStates')->everyThirtyMinutes();

        //每小时执行 富友邮件接收处理
        $schedule->command('fy:receive_email')->hourly();

        //每天2点删除过期未使用的稽核资源
        $schedule->command('cruise:cruise_check_delete_expired')->dailyAt("02:00");

        // 当有待初审任务时，每天三个时间点进行统一提醒。早：9点 中：13点  晚：17点
        $schedule->command('cruise:inspectionTaskSendSms')->dailyAt("09:00")->runInBackground();;
        $schedule->command('cruise:inspectionTaskSendSms')->dailyAt("13:00")->runInBackground();;
        $schedule->command('cruise:inspectionTaskSendSms')->dailyAt("17:00")->runInBackground();;

        // 作废工厂自检表单
        $schedule->command('cruise:selfCheckDetailInvalidCommand')->dailyAt("00:00");

        // 每天8:00推送开发经理对接客户15天未落址消息
        $schedule->command('openShop:site-location-not-confirm')->cron('0 8 * * *');

        // 每天4:00把网规信息加入缓存
        $schedule->command('wanggui:cache-sync-district')->dailyAt('04:00');

        // 观远sku 详情推送 每天晚上8点
        $schedule->command('guanyuan:sourceDataParse')->dailyAt('20:00');

        // 每天1:00 删除旧的银行流水数据
        $schedule->command('check:clear-old-check-stream')->dailyAt('01:00')->runInBackground();

        //每分钟跑的计划任务-评价发送消息
        $schedule->command('appraise:crontabInMinute')->everyMinute();

        // 公众号列表获取
        $schedule->command('calling_cards:sync_official_account')->dailyAt('23:00');

        // 更新销氪地址
        $schedule->command('calling_cards:update_xiaoke_areas')->dailyAt('05:00')->runInBackground();

        //每天6点同步网规点位门店信息
        $schedule->command('wanggui:sync-kf-shop-count')->dailyAt("06:00");

        // 年费自检脚本
        $schedule->command('fee:checkout-shop-fee')->dailyAt("09:05");

        //每天5点同步网规点位
        $schedule->command('wanggui:area-add-geo')->dailyAt("05:00");
        //每天4点刷新选址处理人
        $schedule->command('openshop:scrub_site_location_handler')->dailyAt("04:00");

        //每天4点记账本周期自动同步
        $schedule->command('cashbook:cycle_sync')->dailyAt("04:00");
        //每天4点记账本账单同步自动同步
        $schedule->command('cashbook:cycle_bill_sync')->dailyAt("04:00");
        //每天5点记账本RMS门店营业收入变更同步
        $schedule->command('cashbook:rms_orders_update_sync')->dailyAt("05:00");

        // 招聘数据推送-周
        $schedule->command('feishu:hire-send-notify-v2 --cycle=weekly')
                 ->weeklyOn([
//                     Schedule::MONDAY,
                     Schedule::TUESDAY,
                     Schedule::WEDNESDAY,
                     Schedule::THURSDAY,
                     Schedule::FRIDAY,
                     Schedule::SATURDAY,
                 ], "09:00");
        // 招聘数据推送-月
        $schedule->command('feishu:hire-send-notify-v2 --cycle=monthly')->monthlyOn(1, "09:00");

        // 招聘数据推送-上周
        $schedule->command('feishu:hire-send-notify-v2 --cycle=lastWeek')
                 ->weeklyOn([
                     Schedule::MONDAY,
                 ], "09:00");

        // 每天 19:00 校验 Cookie 是否正常
        $schedule->command('feishu:hire-send-notify-check-cookie')->dailyAt("19:00")->dailyAt("20:00");


        //每天8点沙盘城市点位缓存更新
        $schedule->command('wanggui:update-programming-dot-by-city')->dailyAt("08:05");
        //每天9:40点网规门店信息缓存
        $schedule->command('wanggui:kf-shop-info-cache')->dailyAt("08:59")->runInBackground();

        // 每月20号，同步最新的全国外卖数据至oss
        $schedule->command('waimai:generate-province-city-coordinate')->monthlyOn(20, '02:00');

        // 同步观远正常营业的门店外卖数据
        $schedule->command('waimai:sync-gy-common-shops')->dailyAt("08:58")->runInBackground();

        //每小时执行-排班提醒用户&上班提醒
        $schedule->command('schedule:send_schedule_users_remind')->hourly();

        //每天 x 点提醒用户上传健康证等员工档案信息
        $schedule->command('tools:system_notify:personnelFileMissMsg')->dailyAt('07:30');

        // 每天检测证件照过期时间
        $schedule->command('cruise:check_licence_expired')->dailyAt('02:12');

        // 每天 通知缺少证件的人发信息
//        $schedule->command('cruise:check_licence_expired_notify')->dailyAt('07:40');

        // 巡检项同步
        $hourly = SyncCruiseOrderProjectLazyCommand::EXECUTE_HOUR;
        $schedule->command('cruise:sync_cruise_order_project_lazy')->cron("0 */{$hourly} * * *");

        // 每天10点 查询guanyuan的营业数据,超过15天没有记录的店铺发飞书提醒
//        $schedule->command('open_shop:shop_business_notice')->dailyAt('10:02');

        // 每月21号09:30，招商进度提醒机器人
        $schedule->command('open_shop:investment_schedule_notice')->dailyAt('09:30');

        //每天3:30点刷新夸父门店入驻情况
        $schedule->command('wanggui:refresh-kf-shop-settle-in-situation')->dailyAt("03:30");

        // 考勤每日处理
//        $schedule->command('kms:dailyFieldHandle')->dailyAt('00:00');

        //续签延期到期自动关闭收银&订货
        // $schedule->command('renew:crontabCloseOrderGoodsSystem')->dailyAt('00:00');

        //续签 - 合同：临期门店预处理
        // $schedule->command('contract:handleExpireShop')->dailyAt('10:00');
        $schedule->command('open_shop:provincial_robot_notice')->dailyAt('08:50');

        // 每天9点 检查夸父运营IOS下载code-数量不足提示重新导入
        $schedule->command('kms:checkIosDownloadCode')->dailyAt('09:01');

        // 每天0点30 同步昨天文章数据统计脚本
        $schedule->command('article:statistics_day_script')->dailyAt('00:30');

        // 专题数据每日统计
        $schedule->command('article:categoryDailyStatistics')->dailyAt("00:00");

        // 每小时 同步文章数据统计脚本
        $schedule->command('article:statistics_hot_script')->hourly();

        // 每天4:00同步易快报支行信息
        $schedule->command('ekb:synchronousBranchBankCommand')->dailyAt('04:00');

        // 当天接口调用情况统计
        if (config('app.env') == 'prod' || config('app.env') == 'qa') {
            $startDate = $endDate = date('Ymd');
            $fsRobot   = SendFs::ROBOT_DAILY_SYSTEM_MONITOR;
            $schedule->command("push:api-time-fs-card 10 {$fsRobot} {$startDate} {$endDate}")->dailyAt('22:00')
                     ->runInBackground();
        }

        //每周一早上08点发送通知
//        $schedule->command('mybank:open-pay-notify')->weeklyOn(1, '08:00');

        // 每天早上9点05同步观远门店列表
        $schedule->command('guanyuan:shopList')->dailyAt("09:05")->runInBackground();

        // 每天早上9点20同步城市点位信息
        $schedule->command('wanggui:cacheCityPoint')->dailyAt("09:20")->runInBackground();

        // 每天12点20检查高德web服务的key的可用性
        $schedule->command('amap:checkConfigWebApiKeyStatus')->dailyAt("12:20")->runInBackground();

        // 每天11点50获取点位默认图片
        $schedule->command('wanggui:refresh-amap-image')->dailyAt("11:50")->runInBackground();

        // 每天3点50获取同步开发经理任务信息
        $schedule->command('siteLocation:sync-development-manager-task-info')->dailyAt("03:50")->runInBackground();

        // 每分钟去跑勘址线索状态过期修改
        $schedule->command('siteLocation:update-clue-record-status')->everyMinute();

        // 上海未开通网商的店长通知（2023-10-12 2023-10-24）
        $schedule->command('myBank:no-open-wallet-notify-by-province --provinceCode=0')->dailyAt("06:50")
                 ->runInBackground();

        //同步观远数据-》clickhouse
        if (checkEnv('prod')) {
            $this->syncGuanyuanToClickhouse($schedule);
        }

        // 每小时同步工单-富友流程完成自动修改工单为完成状态
//        $schedule->command('workOrder:autoFuyouSuccess')->hourly();

        // 每天8点 每日汇总开票记录
        $schedule->command('invoice:everyDayScript')->dailyAt("08:00")->runInBackground();

        //开票业务定时脚本
        $this->invoiceGroupCommand($schedule);

        // 每天8点 生炸鸡腿数据推送
//        $schedule->command('open_shop:fried_chicken_leg')->dailyAt('08:00')->runInBackground();

        // 加盟政策状态更新 - 1分钟
        $schedule->command('openShop:updateContractTemplateStatus')->everyMinute()->runInBackground();

        // 加盟订单超时作废 - 10分钟
        $schedule->command('openShop:noPayOrderTimeOutToClose')->everyTenMinutes()->runInBackground();

        // 每天 AI客服-每天会话数据统计
        $schedule->command('chatGroup:dataStatistics')->dailyAt('08:51')->runInBackground();
        $kfStartDate = $kfEndDate = date('Y-m-d');
        $schedule->command("chatGroup:dataStatistics {$kfStartDate} {$kfEndDate}")->dailyAt('18:11')->runInBackground();

        // 每天9点 超期未整改飞书机器人消息提醒-需要每天早晚两次推送（9:00和18:00）
        $schedule->command('cruise:cruiseCheckRectifyNotify')->dailyAt('09:05')->runInBackground();
        $schedule->command('cruise:cruiseCheckRectifyNotify')->dailyAt('18:01')->runInBackground();


        // 自动关闭会话脚本
        $schedule->command('chatGroup:auto-close-session')->everyMinute()->runInBackground();

        // 公有云同步数据
        $this->syncPublicRds($schedule);

        if (checkEnv('prod')) {
            // 销氪线索回传巨量
            $schedule->command('AdvClueCallback:toDy')->everyTenMinutes()->runInBackground();
        }

        // 自检任务每日定时生成
        $schedule->command("cruise:checkSelfTaskGenerateSchedule")->dailyAt("05:00")->runInBackground();
        //自检任务提醒
        $schedule->command("cruise:shop-self-check-notify")->everyFiveMinutes()->runInBackground();

        // 同步销氪相关数据
        $this->syncXiaokeData($schedule);

        // 活动结束后提醒门店上传反馈通知 每1小时查询一次
        $schedule->command('activity:activityEndRemindFeedback')->cron("0 * * * *")->runInBackground();

        //闪屏广告过期自动禁用
        $schedule->command('marketing:change-advertisement-status')->dailyAt("01:00")->runInBackground();
    }


    /**
     * 同步销氪相关数据
     *
     * @param Schedule $schedule
     */
    public function syncXiaokeData(Schedule $schedule)
    {
        // 同步销氪用户数据
        if (checkEnv('prod')) {
            // 销氪线索回传巨量
            $schedule->command('xiaoke:userInit')->dailyAt("00:05")->runInBackground();
        }
    }

    /**
     * 开票业务定时任务
     *
     * @param Schedule $schedule
     */
    public function invoiceGroupCommand(Schedule $schedule)
    {
        if (checkEnv('prod')) {
            $schedule->command('invoice:pollingHandleInvoiceBusiness')->everyFiveMinutes();
        }
    }

    /**
     * //同步观远数据-》clickhouse
     *
     * @param Schedule $schedule
     */
    public function syncGuanyuanToClickhouse(Schedule $schedule)
    {
        //观远外卖每日报表同步clickhouse - clickhouse:sys:gyDailyDeliveryReport
        $schedule->command('clickhouse:sys:gyDailyDeliveryReport')->dailyAt("08:30")->runInBackground();
        $schedule->command('clickhouse:sys:gyDailyDeliveryReport')->dailyAt("09:50")->runInBackground();
        $schedule->command('clickhouse:sys:gyDailyDeliveryReport')->dailyAt("14:00")->runInBackground();

        //观远闭店门店同步clickhouse - clickhouse:sys:gyCloseShop
        $schedule->command('clickhouse:sys:gyCloseShop')->dailyAt("08:32")->runInBackground();
        $schedule->command('clickhouse:sys:gyCloseShop')->dailyAt("09:50")->runInBackground();
        $schedule->command('clickhouse:sys:gyCloseShop')->dailyAt("14:00")->runInBackground();

//        //观远城市新开门店数据-》clickhouse - clickhouse:sys:gyCityNewlyOpenedShop
//        $schedule->command('clickhouse:sys:gyCityNewlyOpenedShop')->dailyAt("03:20")->runInBackground();

        //同步 城市消费签约和新开门店数 -> clickhouse  clickhouse:sys:gyShopCityConsumptionOpenings
        $schedule->command('clickhouse:sys:gyShopCityConsumptionOpenings')->dailyAt("08:34")->runInBackground();
        $schedule->command('clickhouse:sys:gyShopCityConsumptionOpenings')->dailyAt("09:50")->runInBackground();
        $schedule->command('clickhouse:sys:gyShopCityConsumptionOpenings')->dailyAt("14:00")->runInBackground();

        //同步 签约信息表ETL -> clickhouse  clickhouse:sys:sysGyShopSign
        $schedule->command('clickhouse:sys:sysGyShopSign')->dailyAt("08:36")->runInBackground();
        $schedule->command('clickhouse:sys:sysGyShopSign')->dailyAt("09:50")->runInBackground();
        $schedule->command('clickhouse:sys:sysGyShopSign')->dailyAt("14:00")->runInBackground();

        //同步 筹备总览-》clickhouse -> clickhouse:sys:gyPreparatoryOverviewCommand
        $schedule->command('clickhouse:sys:gyPreparatoryOverviewCommand')->dailyAt("08:38")->runInBackground();
        $schedule->command('clickhouse:sys:gyPreparatoryOverviewCommand')->dailyAt("09:50")->runInBackground();
        $schedule->command('clickhouse:sys:gyPreparatoryOverviewCommand')->dailyAt("14:00")->runInBackground();

        // 观远订货数据同步clickhouse - clickhouse:sys:gyDmDaySalesAnalyse
        $schedule->command('clickhouse:sys:gyDmDaySalesAnalyse')->dailyAt("04:00")->runInBackground();
        $schedule->command('clickhouse:sys:gyDmDaySalesAnalyse')->dailyAt("08:30")->runInBackground();
        $schedule->command('clickhouse:sys:gyDmDaySalesAnalyse')->dailyAt("14:05")->runInBackground();
        $schedule->command('clickhouse:sys:gyDmDaySalesAnalyse')->dailyAt("18:00")->runInBackground();

        // 每天凌晨刷新clickHouse索引
        $schedule->command('clickhouse:optimize-table-final')->dailyAt('01:05')->runInBackground();

        // 每小时合并kfos订单记录重复行
        $schedule->command('clickhouse:mergeTableRepeatRow clickhouseKfosData new_orders')->everyTwoHours()
                 ->runInBackground();
        $schedule->command('clickhouse:mergeTableRepeatRow clickhouseKfosData delivery_note_goods')->everyTwoHours()
                 ->runInBackground();
        $schedule->command('clickhouse:mergeTableRepeatRow clickhouseRms kf_shop_business')->everyTwoHours()
                 ->runInBackground();
    }


    /**
     * 同步到公有的数据库中
     *
     * @param Schedule $schedule
     * @return void
     */
    public function syncPublicRds(Schedule $schedule)
    {
        // 同步用户花名到公有数据库中
        $schedule->command('publicRds:publicFs:SyncFsUserInfo')->hourly()->runInBackground();
    }


    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
